//
//  XWXAllXieYiController.m
//  panPanShiWan
//
//  Created by Mr_hi on 2020/5/12.
//  Copyright © 2020 许得诺言. All rights reserved.
//

#import "XWXAllXieYiController.h"
#import <WebKit/WebKit.h>

@interface XWXAllXieYiController ()<WKNavigationDelegate>

/** 进度条 */
@property (nonatomic, strong) UIProgressView *myProgressView;
/** webView */
@property (nonatomic, strong) WKWebView *myWebView;

@end

@implementation XWXAllXieYiController


- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
    [self setNav];
    [self setUI];
}

- (void)setNav {
    UIView *navView = [UIView getAViewWithFrame:CGRectMake(0, 0, ScreenW, NavgationHeight) andBgColor:[UIColor whiteColor]];
    navView.userInteractionEnabled = YES;
    UIView *boVw = [UIView getAViewWithFrame:CGRectZero andBgColor:nil];
    boVw.userInteractionEnabled = YES;
    
    UILabel *titleLab = [UILabel GetLabWithFont:[UIFont fontWithName:@"PingFangSC-Medium" size:18] andTitleColor:XWXPrimaryColor(@"#222222") andTextAligment:1 andBgColor:nil andlabTitle:self.tileStr];
    
    UIButton *backBtn = [UIButton GetBtnWithTitleColor:nil andFont:nil andBgColor:nil andBgImg:nil andImg:kGetImage(@"lc_nav_back_icon") andClickEvent:@selector(backBtnClicked) andAddVC:self andTitle:nil];
    backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -15, 0, 0);
    
    [self.view addSubview:navView];
    [navView addSubview:boVw];
    [boVw addSubview:titleLab];
    [boVw addSubview:backBtn];
    
    [boVw mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(navView);
        make.height.offset(44);
    }];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(boVw);
        make.left.equalTo(boVw);
        make.size.mas_equalTo(CGSizeMake(44, 44));
    }];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backBtn.mas_right);
        make.centerX.centerY.equalTo(boVw);
    }];
}

- (void)setUI {
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F2F2F2"];
    
    UIView *lineVw = [UIView getAViewWithFrame:CGRectMake(0, NavgationHeight, ScreenW, 1) andBgColor:[UIColor colorWithHexString:@"#CCCCCC"]];
    
    [self.view addSubview:self.myWebView];
    [self.view addSubview:self.myProgressView];
    [self.view addSubview:lineVw];
    
    [self.myWebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(NavgationHeight);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-TabRelativeBottomH);
    }];
    [self.myProgressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(NavgationHeight);
        make.left.right.equalTo(self.view);
        make.height.offset(0.8*proW);
    }];
}

- (void)loadData {
    // 进行中文转码
    NSLog(@"webUrl ==  %@",self.urlStr);
    NSURL * strUrl = [NSURL URLWithString:self.urlStr];
    if (strUrl) {
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:strUrl];
        [self.myWebView loadRequest:request];
    }
}

#pragma mark - 进度条监听的代理回调
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self.myWebView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        self.myProgressView.alpha = 1.0f;
        [UIView animateWithDuration:0.3 animations:^{
            [self.myProgressView setProgress:newprogress animated:YES];
        }];
        if (newprogress >= 1.0f) {
            [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                self.myProgressView.alpha = 0.0f;
            } completion:^(BOOL finished) {
                [self.myProgressView setProgress:0 animated:NO];
            }];
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - WKNavigationDelegate method
// 如果不添加这个，那么wkwebview跳转不了AppStore
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSLog(@"%@",webView.URL.absoluteString);
    if ([webView.URL.absoluteString hasPrefix:@"https://itunes.apple.com"] || [webView.URL.absoluteString hasPrefix:@"itms-appss://apps.apple.com"]) {
        [[UIApplication sharedApplication] openURL:navigationAction.request.URL options:@{} completionHandler:nil];
        decisionHandler(WKNavigationActionPolicyCancel);
    }else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

//开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"开始加载网页");
}

//加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"加载完成");
}

//加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"加载失败");
}

- (void)dealloc {
    [self.myWebView removeObserver:self forKeyPath:@"estimatedProgress"];
}

- (void)backBtnClicked {
    if (self.myWebView.canGoBack) {
        [self.myWebView goBack];
    } else {
        if (self.isPushFrom) {
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }
}

#pragma mark - getter and setter
- (UIProgressView *)myProgressView {
    if (_myProgressView == nil) {
        _myProgressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 0)];
        _myProgressView.tintColor = [UIColor whiteColor];
        _myProgressView.trackTintColor = [UIColor colorWithHexString:@"#F2F2F2"];
    }
    return _myProgressView;
}

- (WKWebView *)myWebView {
    if(_myWebView == nil) {
        WKUserContentController *userContentController = [[WKUserContentController alloc] init];
        NSString * webWidth = @"";
        if (@available(iOS 11, *)) {
            webWidth = @"device-width";
        }else{
            webWidth = [NSString stringWithFormat:@"%f",[UIScreen mainScreen].scale * ScreenW];
        }
        NSString *jSString = jSString = [NSString stringWithFormat:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=%@'); document.getElementsByTagName('head')[0].appendChild(meta);",webWidth];

        WKUserScript *wkUserScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        [userContentController addUserScript:wkUserScript];
        WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
        wkWebConfig.userContentController = userContentController;
        _myWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:wkWebConfig];
        _myWebView.navigationDelegate = self;
        _myWebView.opaque = NO;
        _myWebView.multipleTouchEnabled = YES;
        [_myWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    }
    return _myWebView;
}

@end
